// by Xeno
//#define __DEBUG__
#define THIS_FILE "x_isledefense.sqf"
#include "x_setup.sqf"
private ["_isle_grps", "_i", "_retval", "_igrpa", "_igrp", "_make_new", "_units","_posigrp", "_leader"];
if !(call FUNC(checkSHC)) exitWith {};

sleep 35.321;

__TRACE("before isServer check");

if (isServer && {!isNil QGVAR(HC_CLIENT_OBJ)}) exitWith {};

__TRACE("after isServer check");

_old_old_start = [0,0,0];

_isle_grps = [];
for "_i" from 1 to (GVAR(with_isledefense) select 4) do {
	_retval = call FUNC(make_isle_grp);
	__TRACE_1("","_retval");
	_isle_grps set [count _isle_grps, _retval];
	sleep 3.012;
};
__TRACE_1("","_isle_grps");

while {true} do {
	call FUNC(mpcheck);
	sleep 300 + random 300;
	{
		_igrp = _x select 0;
		_make_new = false;
		if (!isNull _igrp) then {
			if ((_igrp call FUNC(GetAliveUnitsGrp)) == 0) then {
				_make_new = true;
			} else {
				_posigrp = _x select 2;
				_leader = leader _igrp;
				if (!isNull _leader) then {
					if (_posigrp distance _leader < 100) then {
						_make_new = true;
					} else {
						_x set [2, position _leader];
					};
				};
			};
		} else {
			_make_new = true;
		};
		if (_make_new) then {
			_units = _x select 1;
			_vecs = _x select 3;
			{if (!isNull _x) then {_x call FUNC(DelVecAndCrew)};sleep 0.01} forEach _vecs;
			sleep 0.01;
			{if (!isNull _x) then {deleteVehicle _x};sleep 0.01} forEach _units;
			_units = nil;
			_vecs = nil;
			_retval = call FUNC(make_isle_grp);
			_isle_grps set [_forEachIndex, _retval];
			sleep 3.012;
		};
		sleep 50 + random 50;
	} forEach _isle_grps;
};